/*
 * 楼盘基本信息详情
 * @author 紫霞 南岛
 * @time 2018/9/22
 * @since 1.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './houseTypeEditStyle.less'
//引用listPage
import classnames from 'classnames/bind';
import { Form, Row, Col, Input, Cascader, Tag, Icon, DatePicker, Select, Button, Upload, Modal, Divider, message} from 'antd'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { cloneDeep, isEmpty } from 'lodash';
import Uploader from 'widget/Upload'


let cx=classnames.bind(styles);
const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;
const InputGroup = Input.Group;

//form默认样式
const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 17 },
};
const formItemTagLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const videoUrlLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const imageLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
}

const routeView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // 获取model中状态机的值
  let { videoUrl, detail, houseTags, houseList, actionType, allAddress, localLayoutMediaList, localSampleMediaList } = modelObj
 
  //添加视频
  function addVideo (name, index) {
    let detailNew = cloneDeep(detail)
    detailNew.video.push("")
    form.setFieldsValue({videoUrl: [" "]})
    dispatch({ type: `${namespace}/updateStore`, payload: { detail: detailNew } })
  }
  //删除视频
  function removeVideo (index) {
    let detailNew = cloneDeep(detail)
    detailNew.video.splice(index, 1)
    resetFields()
    dispatch({ type: `${namespace}/updateStore`, payload: { detail: detailNew } })
  }
  //上传图片公用render
  const uploadButton = (
    <div>
      <Icon type="plus" />
      <div className="ant-upload-text">上传图片</div>
    </div>
  );

  function handlePreview(file) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { previewImage: file.url || file.thumbUrl, previewVisible: true, }
    });
  }
  function normFile(e) {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  //上传图片
  // function uploadChange ( obj, key) {
  //   const { fileList } = obj;
  //   let detailData = cloneDeep(detail)
  //   let localSampleMediaListNew = cloneDeep(localSampleMediaList)
  //   let localLayoutMediaListNew = cloneDeep(localLayoutMediaList)
  //   if(obj.file.status) {
  //     //本地显示图片
  //     key == 'sample' ? (localSampleMediaListNew  = fileList) : (localLayoutMediaListNew = fileList)
  
  //     dispatch({type: `${namespace}/updateStore`, payload: { localSampleMediaList: localSampleMediaListNew, localLayoutMediaList: localLayoutMediaListNew,} });
  //   }
  // }
  //
  function updateImageModel(value,item,idx){
    //console.log(value,item,idx,"update3333")
    let localLayoutMediaListNew = cloneDeep(localLayoutMediaList)
    let localSampleMediaListNew = cloneDeep(localSampleMediaList)
    if(item=='layout'){
      localLayoutMediaListNew.push(value)
      form.setFieldsValue({layoutSpn: localLayoutMediaListNew })
    }else{
      localSampleMediaListNew.push(value)
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { localLayoutMediaList: localLayoutMediaListNew, localSampleMediaList: localSampleMediaListNew }
    });
  };
  
  function removeImgUrl(index,item) {
    let localLayoutMediaListNew = cloneDeep(localLayoutMediaList)
    let localSampleMediaListNew = cloneDeep(localSampleMediaList)
    if (item == 'layout') {
      localLayoutMediaListNew.splice(index,1)
    } else {
      localSampleMediaListNew.splice(index,1)
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { localLayoutMediaList: localLayoutMediaListNew, localSampleMediaList: localSampleMediaListNew }
    });
   
  }
  //提交
  function submit() {
    form.validateFields((err, values) => {
      if(!err){
        dispatch({type: `${namespace}/saveHouse`})
      }
    });
  }
  //数据操作
  function inputChange(value, key, index) {
    let detailData = cloneDeep(detail)
    if(key == 'tags') {
      var tagArr = [];
      !isEmpty(value) && value.map(item => {
        tagArr.push(item.key)
      })
      detailData.tag = tagArr
    } else if(key == 'videoUrl') {
      detailData.video[index] = value;
    } else if(key == 'areaId') {
      detailData.province = value[0]
      detailData.city = value[1]
      detailData.parentProductId = ""
      dispatch({type: `${namespace}/getHouseArea`, payload: {province: value[0], city: value[1]}})
    } else {
      detailData[key] = value;
      if(key == "parentProductId") {
        form.setFieldsValue({parentProductId: value})
      }
    }
    // console.log(value,key)
    dispatch({type: `${namespace}/updateStore`, payload: {detail: detailData}})
  }
  //上传图片限制
  function beforeUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片不能大于2M');
    }
    return isLt2M;
  }
  
  //console.log(localLayoutMediaList,"localLayoutMediaList")
  return (
    <div className={cx('pageLayout')}>
      <div className="public_listMain">
        <div className={styles.functionButton + ' functionButton'}>
          <Button type='primary' onClick={e => submit()} disabled={actionType == 'check' } loading={modelObj.btnLoading}>提交</Button>
        </div>
      </div>
      <Form  className={cx('inline')}>
        <CollapsiblePanels title="新建户型" hideUpDownBtn={true} >
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout} label="户型名称">
                {getFieldDecorator('name', {
                  initialValue: detail.name,
                  rules: [
                    { required: true, whitespace: true, message: '请输入户型名称' },
                  ],
                })(<Input
                    placeholder={actionType == 'check'?"":'请输入户型名称'}
                    disabled={actionType == 'check'}
                    onChange={(e) => { inputChange(e.target.value, 'name') }}
                />)}
              </FormItem>
            </Col>
            <Col className="col" span={11}>
              <FormItem {...formItemLayout} label="户型">
                {getFieldDecorator('typesize', {
                  initialValue: detail.toiletCount ? detail.toiletCount+'':'' ,
                  rules: [
                    { required: true, whitespace: true, message: '请输入户型' },
                    { validator: (rule, value, callback) => {
                      ((value || value + '' === '0') && ('' + value).search(/^(0|[1-9]\d{0,9})$/)) ? callback('限制为10位以内的整数') : callback();
                    } },
                  ],
                })(
                  <Row>
                    <Input
                      style={{width:'30%'}}
                      addonAfter="室"
                      disabled={actionType == 'check'}
                      value={detail.roomCount}
                      onChange={(e) => { inputChange(e.target.value, 'roomCount') }}
                    />
                    <Input
                      style={{width:'30%'}}
                      addonAfter="厅"
                      disabled={actionType == 'check'}
                      value={detail.hallCount}
                      onChange={(e) => { inputChange(e.target.value, 'hallCount') }}
                    />
                    <Input
                      style={{width:'30%'}}
                      addonAfter="卫"
                      disabled={actionType == 'check'}
                      value={detail.toiletCount}
                      onChange={(e) => { inputChange(e.target.value, 'toiletCount') }}
                    />
                  </Row>
                )}
              </FormItem>
            </Col>
            <Col className="col" span={7}>
              <FormItem {...formItemLayout} label="所属项目">
                {getFieldDecorator('parentProductId', {
                   initialValue: detail.parentProductId,
                   rules: [
                    { required: true, whitespace: true, message: '请输入所属项目' },
                  ],
                })(
                  <InputGroup compact>
                    <Cascader style={{width: '50%'}}  disabled={actionType != 'add'} options={allAddress} value={[`${detail.province}`,`${detail.city}` ]}
                                                                                                                                 onChange={(value, selectedOptions)=> inputChange(value, "areaId")} placeholder="请选择项目" />
                    <Select style={{width: '50%'}} notFoundContent={'该省市中无楼盘'} disabled={actionType != 'add'} value={detail.parentProductId}
                            onChange={(e) => inputChange(e, 'parentProductId')}>
                      {
                        houseList && houseList.map((item,index) => (
                          <Select.Option key={`house_${index}`} value={item.productId}>{item.name}</Select.Option>
                        ))
                      }
                    </Select>
                  </InputGroup>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout} label="建筑面积">
                {getFieldDecorator('buildingArea', {
                  initialValue: detail.buildingArea ?  detail.buildingArea+ '' : "",
                  rules: [
                    { required: false, whitespace: true, message: '请输入建筑面积' },
                  ],
                })(<Input
                  placeholder={actionType == 'check'?"":'请输入建筑面积'}
                  addonAfter="㎡"
                  disabled={actionType == 'check'}
                  onChange={(e) => { inputChange(e.target.value, 'buildingArea') }}
                />)}
              </FormItem>
            </Col>
            <Col className="col" span={11}>
              <FormItem {...formItemLayout} label="套内面积">
                {getFieldDecorator('innerArea', {
                  initialValue: detail.innerArea ?detail.innerArea+'':'',
                  rules: [
                    { required: false, whitespace: true, message: '请输入套内面积' },
                  ],
                })(<Row>
                  <Input
                  style={{width:'45%'}}
                  placeholder={actionType == 'check'?"":'最小套内面积'}
                  addonAfter="㎡"
                  value={detail.innerArea ?detail.innerArea+'':'' }
                  disabled={actionType == 'check'}
                  onChange={(e) => { inputChange(e.target.value, 'innerArea') }}
                  />
                  <Input
                  style={{width:'45%'}}
                  placeholder={actionType == 'check'?"":'最大套内面积'}
                  addonAfter="㎡"
                  value={detail.maxInnerArea ? detail.maxInnerArea+'' :''}
                  disabled={actionType == 'check'}
                  onChange={(e) => { inputChange(e.target.value, 'maxInnerArea') }}
                  />
                </Row> )}
              </FormItem>
            </Col>
            <Col className="col" span={7}>
              <FormItem {...formItemLayout} label="参考总价">
                {getFieldDecorator('totalPrice', {
                  initialValue: detail.totalPrice,
                  rules: [
                    { required: false },
                  ],
                })(<Input
                  placeholder={actionType == 'check'?"":'请输入参考总价'}
                  addonAfter="万元"
                  disabled={actionType == 'check'}
                  onChange={(e) => { inputChange(e.target.value, 'totalPrice') }}
                />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                        label="标签">
                {getFieldDecorator('tags', {
                  initialValue: detail.tag,
                  rules: [
                    { required: false, type: "array", whitespace: true, message: '请添加标签' },
                  ],
                })(<Select
                  mode="multiple"
                  style={{ width: '80%' }}
                  placeholder={actionType == 'check'?"":"请选择标签"}
                  disabled={actionType == 'check'}
                  onChange={(e, value) => inputChange(value, "tags")}
                >
                  {houseTags.map((item, idx) => {
                    return (
                      <Select.Option key={item.name}>{item.name}</Select.Option>
                    )
                  })}
                </Select>)}
              </FormItem>
            </Col>
          </Row>
          <Divider />
          {/* <Row>
            <Col className="col" span={11}>
              <FormItem {...videoUrlLayout} label="720°看房URL">
                {getFieldDecorator('720URL', {
                  initialValue: detail.house720 ? detail.house720 : "",
                  rules: [
                    { required: false, whitespace: true, message: '请输入720°看房URL' },
                  ],
                })(<Input
                    placeholder={actionType == 'check'?"":'请输入720°看房URL'}
                    disabled={actionType == 'check'}
                    onChange={(e) => { inputChange(e.target.value, 'house720') }}
                />)}
              </FormItem>
            </Col>
          </Row> */}
          <Row>
            <Col className="col" span={11}>
              <FormItem {...videoUrlLayout} label="VR看房URL">
                {getFieldDecorator('vr', {
                  initialValue: detail.vr ? detail.vr : "",
                  rules: [
                    { required: false, whitespace: true, message: '请输入VR看房URL' },
                  ],
                })(<Input
                    placeholder={actionType == 'check'?"":'请输入VR看房URL'}
                    disabled={actionType == 'check'}
                    onChange={(e) => { inputChange(e.target.value, 'vr') }}
                />)}
              </FormItem>
            </Col>
          </Row>
          <Divider />
          <Row style={{ "borderBottom": 'none' }}>
            {
              !isEmpty(detail.video) && detail.video.map((item, index) => {
                return (
                  <Col span={12} key={`videoUrlarr${index}`}>
                    <Col span={23}>
                      <FormItem
                        key={'videoUrlForm' + index}
                        label="视频url"
                        {...videoUrlLayout}
                      >
                        {getFieldDecorator(`videoUrl_${index}`, {
                          validateTrigger: ['onChange', 'onBlur'],
                          initialValue: item,
                        })(
                          <Input
                             placeholder="请输入" disabled={actionType == 'check'}
                             style={{ width: '95%', marginRight: 8 }} onChange={e => inputChange(e.target.value, "videoUrl", index )} />
                        )}
                      
                      </FormItem>
                    </Col>
                    <Col span={1}>
                      
                        <Icon
                          className="dynamic-delete-button"
                          type="minus-circle-o"
                          style={{ fontSize: 16, color: "#ccc", height: 40 }}
                          onClick={() => removeVideo(index)}
                        />
                    </Col>
                  
                  </Col>
                
                )
              })
            }
          </Row>
          {
            actionType != 'check' && <Row>
              <Col className="col" span={12}>
                <FormItem {...formItemLayout}>
                  <Button type="dashed" onClick={() => addVideo("videoUrl")} style={{ width: '60%',marginLeft:'10%'}}>
                    <Icon type="plus" />添加视频url</Button>
                </FormItem>
              </Col>
            </Row>
          }
        </CollapsiblePanels>
        <CollapsiblePanels title="上传图片" hideUpDownBtn={true} >
          <Row>
            <FormItem {...imageLayout} label='户型图'>
              <Uploader uploadedUrls ={localLayoutMediaList}
                removeFileCbf={(index)=>{removeImgUrl(index,"layout")}}
                uploadSuccessCbf={ (imgUrl) => {updateImageModel(imgUrl,"layout")} }
                showType={actionType == 'check'?'4':'6'}
                fileType='image'
                fileMaxSize='0.5'
                minCropBoxWidth={1500}
                minCropBoxHeight={1120}
                maxFiles='1000' />
               
            </FormItem>
            <Col span={12}>
              <span style={{ color: "#999", marginLeft: "4%" }}>
              {actionType == 'check'?"":"图片分辨率需为1500px*1120px，且文件大小在500kb以下，支持jpg，png格式。"}
              </span>
            </Col>
          </Row>
          <Divider />
          <Row>
            <FormItem {...imageLayout} label="样板间">
            
                <Uploader uploadedUrls ={localSampleMediaList}
                removeFileCbf={(index)=>{removeImgUrl(index,"sample")}}
                uploadSuccessCbf={ (imgUrl) => {updateImageModel(imgUrl,"sample")} }
                showType={actionType == 'check'?'4':'6'}
                fileType='image'
                fileMaxSize='0.5'
                minCropBoxWidth={1500}
                minCropBoxHeight={1120}
                maxFiles='1000' />
            
            </FormItem>
            <Col span={12}>
              <span style={{ color: "#999", marginLeft: "4%" }}>
              {actionType == 'check'?"":"图片分辨率需为1500px*1120px，且文件大小在500kb以下，支持jpg，png格式。"}
              </span>
            </Col>
          </Row>
          <Divider />
        </CollapsiblePanels>
      </Form>

    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
